<?php
namespace app\index\model;

use think\Model;
use think\Db;
use think\Cache;
class Weixin extends Model{
    public function valid(){
        $echoStr = $_GET["echostr"];
        if($this->checkSignature() && $echoStr){
            header('content-type:text;charset=utf-8');
            echo ltrim($echoStr);
            exit();
        }
    }
    //验证服务器
    private function checkSignature()
    {
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        $token = TOKEN;
        //微信提交参数放入数组
        $tmpArr = array($token, $timestamp, $nonce);
        //①将token、timestamp、nonce三个参数进行字典序排序
        sort($tmpArr, SORT_STRING);
        //②将三个参数字符串拼接成一个字符串进行sha1加密
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );
        //③开发者获得加密后的字符串可与signature对比
        if( $tmpStr == $signature){
            return true;
        }else{
            return false;
        }
    }


    public function responseMsg()
    {
        $postStr = file_get_contents("php://input");
        //$postStr = $GLOBALS['HTTP_RAW_POST_DATA'];
        if (!empty($postStr)){
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $RX_TYPE = trim($postObj->MsgType);
            //用户发送的消息类型判断
            switch ($RX_TYPE)
            {
                case "text":    //文本消息
                    $result = $this->receiveText($postObj);
                    break;
                case "image":   //图片消息
                    $result = $this->receiveImage($postObj);
                    break;

                case "voice":   //语音消息
                    $result = $this->receiveVoice($postObj);
                    break;
                case "video":   //视频消息
                    $result = $this->receiveVideo($postObj);
                    break;
                case "location"://位置消息
                    $result = $this->receiveLocation($postObj);
                    break;
                case "link":    //链接消息
                    $result = $this->receiveLink($postObj);
                    break;
                default:
                    $result = "unknow msg type: ".$RX_TYPE;
                    break;
            }
            echo $result;
            //return $result;
        }else {
            echo "";
            exit;
        }
    }

    // 接收文本消息

    private function receiveText($object)
    {
        try{
            $years = date('Y-m-d');
            $res = Cache::get('access_token');
            $access_token = $res["access_token"];
            $openid = $object->FromUserName;
            $get_user_info_url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=$access_token&openid=$openid&lang=zh_CN";
            $userinfo = (array)$this->getJson($get_user_info_url);
            $xx= (array)$object;
            $save['openid'] = $openid;
            $save['nickname'] =  $userinfo['nickname'];
            $save['remark'] =  $userinfo['remark'];
            $save['date'] = date('Ymd');
            $save['time'] = $this->msectime();
            $save['type'] = 1;
            $save['content'] = $xx['Content'];
            $save['file_path'] = $openid.'/'.$years;
            Db::name('download_info')->insert($save);
            $data = $xx['Content'];
            $content = "你发送的是文本，内容为：".$object->Content;
            $this->write_log($data,$openid);
            $result = $this->transmitText($object,$content);
            return $result;
        }catch (\Exception $e){
            return $this->transmitText($object,$e->getMessage());
        }
    }

    //接收图片消息
    private function receiveImage($object)
    {
        try{
            $years = date('Y-m-d');
            $res = Cache::get('access_token');
            $access_token = $res["access_token"];
            $openid = $object->FromUserName;
            $get_user_info_url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=$access_token&openid=$openid";
            $userinfo = (array)$this->getJson($get_user_info_url);
            $path = ROOT_PATH.'/public/static/weixin/'.$openid.'/'.$years.'/'.$this->msectime().'.jpg';
            $dir_name=dirname($path);
            if(!file_exists($dir_name))
            {
                //iconv防止中文名乱码
                $name = mkdir(iconv("UTF-8", "GBK", $dir_name),0777,true);
            }
            $dir = '/weixin/'.$openid.'/'.$years.'/'.$this->msectime().'.jpg';
            $save['openid'] = $openid;
            $save['nickname'] =  $userinfo['nickname'];
            $save['remark'] =  $userinfo['remark'];
            $save['date'] = date('Ymd');
            $save['time'] = $this->msectime();
            $save['type'] = 2;
            $save['content'] = $dir;
            $save['file_path'] = $openid.'/'.$years;
            Db::name('download_info')->insert($save);
            $content = "你发送的图片已接收";
            $contents = file_get_contents($object->PicUrl);
            $res = file_put_contents($path, $contents);
            if($res){
                $result = $this->transmitText($object, $content);
            }else{
                $result = $this->transmitText($object, '图片接收失败，请重新发送该图片');
            }
            return $result;
        }catch (\Exception $e){
            return $this->transmitText($object,$e->getMessage());
        }
    }

    //获取毫秒时间戳
    public function msectime() {
        list($t1, $t2) = explode(' ', microtime());
        return (float)sprintf('%.0f',(floatval($t2)+floatval($t1))*1000);
    }
    //接收语音消息

    private function receiveVoice($object)
    {
        $content = "你发送的是语音，媒体ID为：".$object->MediaId;
        $result = $this->transmitText($object, $content);
        return $result;
    }

    //接收视频消息
    private function receiveVideo($object)
    {
        $content = "你发送的是视频，媒体ID为：".$object->MediaId;
        $result = $this->transmitText($object, $content);
        return $result;
    }

    //接收位置消息

    private function receiveLocation($object)
    {
        $content = "你发送的是位置，纬度为：".$object->Location_X."；经度为：".$object->Location_Y."；缩放级别为：".$object->Scale."；位置为：".$object->Label;
        $result = $this->transmitText($object, $content);
        return $result;
    }

//接收连接
    private function receiveLink($object)
    {
        $content = "你发送的是链接，标题为：".$object->Title."；内容为：".$object->Description."；链接地址为：".$object->Url;
        $result = $this->transmitText($object, $content);
        return $result;
    }
//回复
    private function transmitText($object, $content)
    {
        $textTpl = "<xml><ToUserName><![CDATA[%s]]></ToUserName><FromUserName><![CDATA[%s]]></FromUserName><CreateTime>%s</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[%s]]></Content></xml>";
        $result = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time(),$content );
        return $result;
    }
//log
    public function write_log($data,$name){
        $years = date('Y-m-d');
        //设置路径目录信息
        $url = './public/static/weixin/'.$name.'/'.$years.'/'.$this->msectime().'.txt';
        $dir_name=dirname($url);
        //目录不存在就创建
        if(!file_exists($dir_name))
        {
            //iconv防止中文名乱码
            $res = mkdir(iconv("UTF-8", "GBK", $dir_name),0777,true);
        }
        $fp = fopen($url,"a");//打开文件资源通道 不存在则自动创建
        fwrite($fp,$data."\r\n");//写入文件
        fclose($fp);//关闭资源通道
    }

    //获取url返回值
    public function getJson($url){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($ch);
        curl_close($ch);
        return json_decode($output, true);
    }
    //获取Token
    public function getAccessToken(){
        $appid = "wx9930ba0c9197fee4";
        $secret = "39411b7774294b3a8149f556a9e7d3d1";
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($ch);
        curl_close($ch);
        $res = json_decode($output, true);
        //$this->write_log($res['access_token'],2);
        if(isset($res['access_token'])){
            Cache::set('access_token',$res,3600);
        }else{
            $this->getAccessToken();
        }

    }



}